# -*- coding: utf-8 -*-
import cv2
from PyQt5.Qt import QImage, QPixmap, QSize, Qt
import numpy as np


class ImageShow:
    def __init__(self, img=None, label=None):
        self.img = img
        self.image_data = None
        self.label = label
        self.img_h, self.img_w = 480, 640
        self.scale_ratio = None

    def show_image(self):
        try:
            # image = cv2.imread(self.img)   # flag=1 or 3
            image = ImageShow.cvRead(self.img)
            self.image_data = image
            # print(image.shape)
            ih, iw, _ = image.shape
            self.img_h, self.img_w = ih, iw
            new_image = self.size_adaptation(image)

            self.scale_ratio = float(new_image.shape[0] / ih)    # 默认float64
            new_image = cv2.cvtColor(new_image, cv2.COLOR_BGR2RGB)
            # self.image_data = new_image
            qImage = QImage(new_image.data, new_image.shape[1], new_image.shape[0],     # new_image.shape: (526, 702, 3)
                            new_image.shape[2]*new_image.shape[1], QImage.Format_RGB888)
            self.label.setPixmap(QPixmap.fromImage(qImage))

        except Exception as e:
            print(repr(e))

    def save_img(self, root):
        """
        保存label中的image
        """
        pixmap = self.label.pixmap()
        scaled_img = pixmap.scaled(QSize(self.img_w, self.img_h))
        scaled_img.save(root)

    def ndarray2qimage(self, img):
        new_image = self.size_adaptation(img)
        new_image = cv2.cvtColor(new_image, cv2.COLOR_BGR2RGB)
        qImage = QImage(new_image.data, new_image.shape[1], new_image.shape[0],
                        new_image.shape[2] * new_image.shape[1], QImage.Format_RGB888)
        return qImage

    def qimage2ndarray(self):
        qImage = self.label.pixmap().toImage()
        size = qImage.size()
        s = qImage.bits().asstring(size.width() * size.height() * qImage.depth() // 8)
        arr = np.fromstring(s, dtype=np.uint8).reshape((size.height(), size.width(), qImage.depth() // 8))  # BGRA
        # ImageShow.cv_show('hah', arr)  # 测试
        gray = cv2.cvtColor(arr, cv2.COLOR_BGRA2GRAY)
        gray = cv2.resize(gray, dsize=(640, 480))
        return gray

    def size_adaptation(self, img):
        ih, iw, _ = img.shape
        w, h = self.label.geometry().width(), self.label.geometry().height()
        # 保持纵横比
        if (ih / iw) >= (h / w):
            nw = int(iw / ih * h)
            new_image = cv2.resize(img, (nw, h))
        else:
            nh = int(ih / iw * w)
            new_image = cv2.resize(img, (w, nh))
        return new_image

    def size_adaptation2(self, img):
        """
        另一种图像自适应
        """
        pixmap = QPixmap(img).scaled(self.label.size(), aspectRatioMode=Qt.KeepAspectRatio)
        self.label.setPixmap(pixmap)
        self.label.repaint()

    @staticmethod
    def rgb2gray(img):
        if len(img.shape) == 3:
            image = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        else:
            image = img
        return image

    @staticmethod
    def cvRead(filepath):
        """
        # 读取图像，解决imread不能读取中文路径的问题
        """
        cv_img = cv2.imdecode(np.fromfile(filepath, dtype=np.uint8), -1)  # 图片数据转为mat数据
        # imdecode读取的是rgb，如果后续需要opencv处理的话，需要转换成bgr，转换后图片颜色会变化
        # cv_img=cv2.cvtColor(cv_img,cv2.COLOR_RGB2BGR)
        return cv_img

    @staticmethod
    def cv_show(name, img):
        cv2.imshow(name, img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()


if __name__ == '__main__':
    img = "E:/缺陷/Detect_interf/resource/images/18.png"
    Image = ImageShow(img)



